package com.cryptape.cita_wallet.fragment.wallet

import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.RelativeLayout
import android.widget.Toast
import com.alm.token.MyApp
import com.alm.token.R
import com.alm.token.ui.activity.MessageActivity
import com.alm.token.ui.data.bean.UserWalletData
import com.alm.token.ui.viewpagefragment.WalletPageFrag.dataBean
import com.alm.token.utils.CommonUtil
import com.alm.token.widget.HomeGridLayoutNew
import com.cryptape.cita_wallet.activity.AddWalletActivity
import com.cryptape.cita_wallet.activity.CloudMinerActivity
import com.cryptape.cita_wallet.activity.MainActivity.REQUEST_CODE_SCAN
import com.cryptape.cita_wallet.activity.MinerIncomeActivity
import com.cryptape.cita_wallet.activity.addtoken.AddTokenActivity
import com.cryptape.cita_wallet.bean.AddDataItem
import com.cryptape.cita_wallet.event.*
import com.cryptape.cita_wallet.fragment.NBaseFragment
import com.cryptape.cita_wallet.item.Token
import com.cryptape.cita_wallet.item.Wallet
import com.cryptape.cita_wallet.util.CurrencyUtil
import com.cryptape.cita_wallet.util.db.DBWalletUtil
import com.cryptape.cita_wallet.util.permission.PermissionUtil
import com.cryptape.cita_wallet.util.permission.RuntimeRationale
import com.cryptape.cita_wallet.view.AddDataPopupWindow
import com.cryptape.cita_wallet.view.TitleBar
import com.cryptape.cita_wallet.view.WalletAssetsView
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Permission
import com.yzq.zxinglibrary.android.CaptureActivity
import kotlinx.android.synthetic.main.custom_titlebar.view.*
import kotlinx.android.synthetic.main.fragment_wallet.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by BaojunCZ on 2018/11/19.
 */
class WalletFragment : NBaseFragment(), View.OnClickListener, HomeGridLayoutNew.BtnInterface {

    override fun onTab(view: View?) {
        when (view!!.id) {
            R.id.tab1 -> {
                AndPermission.with(activity)
                        .runtime().permission(*Permission.Group.CAMERA)
                        .rationale(RuntimeRationale())
                        .onGranted {
                            val intent = Intent(activity, CaptureActivity::class.java)
                            intent.putExtra(com.yzq.zxinglibrary.common.Constant.INTENT_ZXING_CONFIG, MyApp.getZxingConfig());

                            startActivityForResult(intent, REQUEST_CODE_SCAN)

                        }
                        .onDenied { permissions ->
                            PermissionUtil.showSettingDialog(activity, permissions)
                        }
                        .start()
            }
            R.id.tab2 -> startActivity(Intent(activity, CloudMinerActivity::class.java))
            R.id.tab3 -> {
                 Toast.makeText(getActivity(),getString(R.string.Not_open_yet),Toast.LENGTH_SHORT).show();

//                var token = Token(ConstantUtil.ETH_MAINNET, ConstantUtil.ETH, ConstantUtil.ETHEREUM_MAIN_ID);
//                var intent = Intent(getContext(), ExchangeActivity::class.java);
//                intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
//                intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.getExchangeContract());
//                startActivity(intent);
            }
            R.id.tab4 -> {
                var intent = Intent(getContext(), MinerIncomeActivity::class.java);
                startActivity(intent);
            }
        }
    }

    companion object {
        val TAG = WalletFragment::class.java.name!!
    }

    private var mWalletAssetsView: WalletAssetsView? = null
    private var mTitleBar: TitleBar? = null
    private var mRlMessageNote: RelativeLayout? = null;

    private var mTokenItemList: MutableList<Token> = mutableListOf()
    private lateinit var mAdapter: WalletTokenAdapter
    private lateinit var mCircleAnim: Animation
    private var mHomeGridLayoutNew: HomeGridLayoutNew? = null;

    override val contentLayout: Int
        get() = R.layout.fragment_wallet

    override fun initView() {
        mWalletAssetsView = findViewById(R.id.view_wallet_assets) as WalletAssetsView
        mTitleBar = findViewById(R.id.title) as TitleBar

        mRlMessageNote = findViewById(R.id.rl_message_note) as RelativeLayout
//        mHomeGridLayoutNew = findViewById(R.id.wdgt_homegridly) as HomeGridLayoutNew

        title.mTitleBarRightDefaultView.setCompoundDrawables(null, null, null, null);
    }

    override fun initData() {
        loadExchangeBtn()
        recycler.layoutManager = LinearLayoutManager(activity)
        recycler.isNestedScrollingEnabled = false
        reloadTokens()
        loadData()
    }

    override fun initAction() {
        iv_right_arrow.setOnClickListener(this)
        tv_add_token.setOnClickListener(this)
        iv_refresh.setOnClickListener(this)
        tv_moresysmsg.setOnClickListener(this)
        tv_sysmsg.setOnClickListener(this)
        wdgt_homegridly.setBtnInterface(this)

        mTitleBar!!.setOnRightClickListener {
            var data: List<AddDataItem> = ArrayList<AddDataItem>();

            var popupWindow = AddDataPopupWindow(activity, data);
            popupWindow.showAsDropDown(mTitleBar!!.title_bar_right, 0, 10);
        }
        mTitleBar!!.setOnLeftClickListener {
            //            if (DBWalletUtil.getAllWallet(activity).size >= 1)
//            {
//                activity!!.startActivity(Intent(activity, ChangeWalletActivity::class.java))
//                activity!!.overridePendingTransition(R.anim.wallet_activity_in, 0)
//            }
//            else {
//                activity!!.startActivity(Intent(context, AddWalletActivity::class.java))
//            }
            activity!!.startActivity(Intent(context, CloudMinerActivity::class.java))
        }
        swipe_refresh_layout.setOnRefreshListener {
            iv_refresh.visibility = View.GONE
            refreshTokens(false)
        }

        mRlMessageNote!!.setOnClickListener {
            val intent = Intent(context, MessageActivity::class.java)
            intent.putExtra("type", 1)
            activity!!.startActivity(intent)

//            activity!!.startActivity(Intent(context, MessageListActivity::class.java))
        }
    }

    //reload list after exchanging wallet
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onWalletSaveEvent(event: TokenRefreshEvent) {
        loadExchangeBtn()
        reloadTokens()
    }

    //refresh list after adding token
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAddTokenEvent(event: AddTokenRefreshEvent) {
        reloadTokens()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCurrencyRefreshEvent(event: CurrencyRefreshEvent) {
        mWalletAssetsView!!.setCurrency()
        mWalletAssetsView!!.setTotalAssets(resources.getString(R.string.wallet_assets_start_query))
        reloadTokens()
    }

    //Subscribe token balance and price
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTokenBalaceEvent(event: TokenBalanceEvent) {
        var isLoadedAll = true
        var totalAssets = 0.0
        mTokenItemList.forEachIndexed { index, item ->
            if (event.item.contractAddress == item.contractAddress && event.item.chainId == item.chainId
                    && event.item.name == item.name && event.item.symbol == item.symbol) {
                mTokenItemList[index] = event.item
                mTokenItemList[index].loaded = true
                totalAssets += event.item.currencyPrice
            } else {
                if (!item.loaded) isLoadedAll = false
            }
            totalAssets += item.currencyPrice
            if (totalAssets != 0.0) {
                mWalletAssetsView!!.setTotalAssets("≈" + CurrencyUtil.getCurrencyItem(context).symbol
                        + " " + CurrencyUtil.formatCurrency(totalAssets))
            }
        }
        if (isLoadedAll) {
            finishRefresh()
            if (totalAssets == 0.0) mWalletAssetsView!!.setTotalAssets(resources.getString(R.string.wallet_token_no_assets))
        }
    }

    override fun onClick(view: View?) {
        when (view!!.id) {
            R.id.iv_right_arrow, R.id.tv_add_token -> startActivity(Intent(activity, AddTokenActivity::class.java))
            R.id.iv_refresh -> {
                if (swipe_refresh_layout.isEnabled)
                    refreshTokens(true)
            }

            R.id.tv_moresysmsg -> {
//                showToast("更多公告click");
                var intent = Intent(activity, MessageActivity::class.java);
                intent.putExtra("type", 1);
                startActivity(intent);
            }
            R.id.tv_sysmsg -> {
                var intent = Intent(activity, MessageActivity::class.java);
                intent.putExtra("type", 1);
                startActivity(intent);
//                showToast("公告详情");
//                if (EmptyUtils.isNotEmpty(tv_sysmsg.getTag()) && tv_sysmsg.getTag() instanceof UserWalletData.DataBean.SysMsgBean::class.java) {
//                    var intent1 =  Intent(activity, MessageDetailActivity::class.java);
//                    intent1.putExtra("intentType", 1);
//                    intent1.putExtra("sysMsgBean", (UserWalletData.DataBean.SysMsgBean::class.java) (tv_sysmsg.getTag()));
//                    startActivity(intent1);
//                }
            }
//            break;
        }
    }

    private fun getMyTokens(mWallet: Wallet?) {
        var list = mWallet!!.tokens

        if (mWallet != null) {
            mWalletAssetsView!!.setAddress(mWallet.address);
            mWalletAssetsView!!.setName(mWallet.name)
        }
        mTokenItemList.clear()
        list.forEachIndexed { _, tokenItem ->
            if (tokenItem.selected)
                mTokenItemList.add(Token(tokenItem))
        }
        if (mTokenItemList.size == 0) {
            finishRefresh()
            mWalletAssetsView!!.setTotalAssets(resources.getString(R.string.wallet_token_no_assets))
        }
    }

    private fun reloadTokens() {
        startIvRefresh()
        var mWallet = DBWalletUtil.getCurrentWallet(context)
        if (mWallet == null) {
            startActivity(Intent(context, AddWalletActivity::class.java))
            return
        }
        getMyTokens(mWallet)
        mAdapter = WalletTokenAdapter(DBWalletUtil.getCurrentWallet(context).address, mTokenItemList)
        recycler.adapter = mAdapter
    }

    private fun refreshTokens(isIvRefresh: Boolean) {
        if (isIvRefresh) {
            startIvRefresh()
        }
        var mWallet = DBWalletUtil.getCurrentWallet(context)
        if (mWallet == null) {
            startActivity(Intent(context, AddWalletActivity::class.java))
            return
        }
        getMyTokens(mWallet)
        EventBus.getDefault().post(QueryMIDEvent());
        mAdapter.refresh(mTokenItemList)
    }

    //iv_refresh animation
    private fun startIvRefresh() {
        swipe_refresh_layout.isEnabled = false
        mCircleAnim = AnimationUtils.loadAnimation(context, R.anim.anim_round_rotate)
        val interpolator = LinearInterpolator()
        mCircleAnim.interpolator = interpolator
        iv_refresh.startAnimation(mCircleAnim)
    }

    private fun finishRefresh() {
        swipe_refresh_layout.isRefreshing = false
        swipe_refresh_layout.isEnabled = true
        iv_refresh.clearAnimation()
        iv_refresh.visibility = View.VISIBLE
    }

    private fun loadExchangeBtn() {
//        if (DBWalletUtil.getAllWalletName(activity!!).size > 1) {
//            mTitleBar!!.setRightImage(R.drawable.ic_wallet_exchange)
//        } else {
//            mTitleBar!!.setRightImage(R.drawable.ic_wallet_rec_add)
//        }
//        mTitleBar!!.setRightImage(R.drawable.icon_add)
    }
//    @BindView(R.id.tv_sysmsg)
//    TextView tvSysmsg;
    private var sysMsg: List<UserWalletData.DataBean.SysMsgBean> = ArrayList();
    private var sysMsgNew: List<UserWalletData.DataBean.SysMsgBean> = ArrayList();
    protected fun loadData() {
        if (dataBean != null) {
//            Toast.makeText(getContext(), "1111ValidFragment 19999999999", Toast.LENGTH_SHORT).show();
            sysMsg = dataBean.getSysMsg();

//            sysMsgNew!!.clear;
            sysMsgNew =sysMsg;

            if (sysMsg != null && sysMsg!!.size != 0) {
                tv_sysmsg.setText(sysMsg.get(0).getTitle());
                left_horn.setText("[" + CommonUtil.getDateTimeFromMillisecond(sysMsg.get(0).getCreateTime()).split(" ")[0] + "]");
                tv_sysmsg.setTag(sysMsg.get(0));
            }
//            if (sysMsg != null && sysMsg.size() != 0 && !rlySysmsgBody.isShown()) {
////            mRecyclerView.setVisibility(View.VISIBLE);
//
//                mAdapter = new MyAdapter (getActivity(), sysMsg);
//                mRecyclerView.setAdapter(mAdapter);
//
//
////            tvSysmsg.setText(sysMsg.get(sysMsg.size() - 1).getTitle());
////            tvSysmsgLeftTime.setText("[" + CommonUtil.getDateTimeFromMillisecond(sysMsg.get(sysMsg.size() - 1).getCreateTime()).split(" ")[0] + "]");
////            tvSysmsg.setTag(sysMsg.get(sysMsg.size() - 1));
//            } else if (sysMsg != null && sysMsg.size() != 0) {
//
////                mRecyclerView.setVisibility(View.GONE);
//                rlySysmsgBody.setVisibility(View.VISIBLE);
////            tvSysmsg.setText(sysMsg.get(sysMsg.size() - 1).getTitle());
////            tvSysmsgLeftTime.setText("[" + CommonUtil.getDateTimeFromMillisecond(sysMsg.get(sysMsg.size() - 1).getCreateTime()).split(" ")[0] + "]");
////            tvSysmsg.setTag(sysMsg.get(sysMsg.size() - 1));
//            } else {
////                mRecyclerView.setVisibility(View.GONE);
////            rlySysmsgBody.setVisibility(View.GONE);
//            }


        }
    }

}